Ext.BLANK_IMAGE_URL='../resources/images/default/s.gif';
/**
 * @include "../js/FilterTree.js"
 */
Ext.onReady(function() {
	var treeUrl='../hf/treeBase.do?action=treeNode&clazz=TabType';
	var nodeUrl='../hf/formBase.do?action=ajaxEdit&&clazz=TabType';
	var saveUrl='../hf/treeBase.do?action=save&clazz=TabType';
	var deleteUrl='../hf/formBase.do?action=ajaxDelete&&clazz=TabType';
	var sortUrl='../hf/treeBase.do?action=sort&clazz=TabType';
	var getImageUrl='../hf/treeMenu.do?action=getImages';
	//读取图片的store
    var store=new Ext.data.JsonStore({
                    url: getImageUrl,
                    baseParams :{imageDir :'/images/menu/2/icon/'},
                    root: 'images',
                    fields: ['name', 'url']
                });
    
    var comboBoxImage = new Ext.ux.ComboImage( {
        store : store,
        emptyText : '请选择',
        triggerAction : 'all',
        displayField : 'name',       
        valueField:'url',
        fieldLabel : '菜单图片',
        labelStyle :{width:200},
        hiddenName: 'icon',
        //anchor : '100%',
        readOnly : true
    });
                
    var north = new Ext.Panel({
        layout:'anchor',
        region:'north',
        margins : '0 0 0 0',
        height:25,
        items:[
           new Ext.Toolbar({
                cls:'top-toolbar',
                items:['->', {
                    tooltip:'Hide Inherited Members',
                    iconCls: 'icon-hide-inherited',
                    enableToggle: true,
                    toggleHandler : function(b, pressed){
                         //mainPanel[pressed ? 'addClass' : 'removeClass']('hide-inherited');
                    }
                }, '-', {
                    tooltip:'Expand All Members',
                    iconCls: 'icon-expand-members',
                    enableToggle: true,
                    toggleHandler : function(b, pressed){
                       // mainPanel[pressed ? 'addClass' : 'removeClass']('full-details');
                    }
                }]
            })
        ]
        
    });
    //west的tree
    var tree=new Ext.ux.FilterTree({
        id:'tree',
        border:false,
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        rootVisible: false,
        containerScroll: true, 
        loader:new Ext.tree.TreeLoader({
            dataUrl:treeUrl,
            preloadChildren:true
        })
    });
    
    /*new Ext.tree.TreeSorter(tree, 
            {folderSort:true,
                property:'id',
                dir:'desc'});*/
    
    /*new Ext.tree.TreeEditor(tree,{
        allowBlank    : false
    });*/
    
    var root=new Ext.tree.AsyncTreeNode({
        text:'根节点',
        id:'10000'
    });
    
    
    tree.setRootNode(root);
    //tree.render();
    root.expand();
    
    //conent中的表单    
    var form = new Ext.FormPanel({
        region : 'center',
        margins : '0 0 0 0',
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        width: '100%',
        

        items: [{
            xtype:'fieldset',
            title: '菜单信息',
            collapsible: false,
            autoHeight: true,            
            defaults: {width: 250,
                labelStyle :{width:200}
            },
            defaultType: 'textfield',
            items :[{
                    id:'uniqueCode',
                    xtype:'hidden',
                    name: 'uniqueCode'
                },{
                    id:'parentId',
                    xtype:'hidden',
                    name: 'parentId'
                },{
                    fieldLabel: '父菜单名称',
                    name: 'fatherMenuName',
                    disabled :true
                },{
                    fieldLabel: '类别名称',
                    name: 'text'
                },comboBoxImage,{
                    fieldLabel: '备注',
                    name: 'remark'
                },{
                    fieldLabel: '排列号',
                    name: 'serialNumber'
                }
            ]
        }],

        buttons: [{
            text: '保存',
            handler:function(){//start function按钮处理函数

                if(form.getForm().isValid()){//表单是否通过交验，通过责提交表单，否则弹出错误窗口
                    form.getForm().submit({
                        waitMsg:'保存数据...',
                        url:saveUrl,
                        success:function(form,action){
                            Ext.MessageBox.alert('消息：','保存成功');
                            var n;
                            var loadScope;
                            if(tree.getNodeById(form.getValues(false).uniqueCode)!=undefined){
                                n=tree.getNodeById(form.getValues(false).uniqueCode);
                                loadScope=n.parentNode;
                            }else{
                                n=tree.getSelectionModel().getSelectedNode();
                                loadScope=n;
                            }
                            //var n=tree.getNodeById(form.getValues(false).uniqueCode)||tree.getSelectionModel().getSelectedNode(); 
                             //重新加载节点
                            tree.getLoader().load(loadScope,function(treeLoader, node){
                                node.expand();
                            });
                        },
                        failure:function(form,action){
                            Ext.MessageBox.alert('有错误:', action.result.errors);
                        }
                    });
                }else{
                    Ext.MessageBox.alert('消息：','有错误，请重新录入信息！');
                }
            }               
            },{
            text: '重置',
            handler:function(){//start function按钮处理函数
                    form.getForm().reset();
                }//end function 
        }]
    });
    //右键菜单
    var contextmenu=new Ext.menu.Menu({
        id:'theContextMenu',
        items:[{
            text:'添加',
            iconCls:'add',
            handler:function(){             
                var node=tree.getSelectionModel().getSelectedNode(); 
                CreateTreeNode(node,contextmenu,form);                            
            }
        },{
            text:'删除',
            iconCls:'remove',
            handler:function(){
                var node=tree.getSelectionModel().getSelectedNode(); 
                Ext.Msg. confirm('确认框', '您确定要删除'+node.text+'菜单吗？', function(btn, text){
                    if (btn == 'yes'){
                        AjaxRequest(deleteUrl,{uniqueCode:node.id},node);
                    }
                },node);
            }
        },'-',{
            text:'刷新',
            iconCls:'left-menu-refresh',
            handler:function(){
                var loadScope = tree.getSelectionModel().getSelectedNode();
                tree.getLoader().load(loadScope,function(treeLoader, node){
                    node.expand();
                });
                contextmenu.hide();
            }
        }]
    });
    //在treePanel中，右击非树节点时的菜单
    var treeContextmenu = new Ext.menu.Menu({
        id:'treeContextMenu',
        items:[{
            text:'添加',
            iconCls:'add',
            handler:function(){
                CreateTreeNode(tree.root,treeContextmenu,form);
            }
        },'-',{
            text:'刷新',
            iconCls:'left-menu-refresh',
            handler:function(){
                tree.getLoader().load(tree.root,function(treeLoader, node){
                    node.expand();
                });
                treeContextmenu.hide();
            }
        }]
    });
    //创建树节点
    function CreateTreeNode(node, cmenu, form) {

        var newNode = new Ext.tree.TreeNode({
            text : '新菜单',
            leaf : false,
            newNode : true
        });

        if (node.leaf) {
            node.leaf = false;
        }
        node.expand();
        node.appendChild(newNode);

        treeContextmenu.hide();
        form.form.reset();
        form.form.setValues({
            fatherMenuName : node.text,
            menuName : '新菜单',
            parentId : node.id
        });
    }
    // 从服务器读取树节点
    function AjaxRequest(url,params,scope){
        Ext.Ajax.request({                 // 调用Ajax发送请求到后台
            scope:scope,
            url:url,                    // 删除grid数据的url.
            success:function(transport){                // 处理成功后返回的函数
                var oXmlDom=transport.responseText;
                if(oXmlDom!=''){                  
                    var content=eval(oXmlDom);
                    Ext.MessageBox.alert("有错误：",content.errors)
                }else{
                    Ext.MessageBox.alert('消息：','删除成功');
                    this.remove();
                }
            },
            failure:function(){             //处理后台删除失败的函数
                Ext.MessageBox.alert('消息','删除失败!');
            },
            params:params
        });
    }
    
    tree.on('contextmenu',function(node,e){
        e.stopEvent();                 //禁止默认菜单弹出
        node.select();                      //选择当前节点
        contextmenu.showAt(e.getXY());
    });
   
    //添加菜单单击事件
    tree.on('click',function(node,e){
        e.preventDefault();                 //禁止默认菜单弹出
        var nodeId
        if(node.newNode){
            nodeId='';
        }else{
            nodeId=node.id;
        }
        form.form.reset();
        
        
        form.form.load({//start load 参数设置
            url:nodeUrl,
            params:{
                uniqueCode:nodeId
            },
            failure:function(form,action){
                Ext.MessageBox.alert('有错误:', action.result.errors);
                //debuger;
                form.reset();
                form.setValues({
                        fatherMenuName:this.parentNode.text,
                        menuName:this.text,
                        parentId:this.parentNode.id});
            },
            success:function(form,action){
                //debugger;
                var parentNode=this.parentNode ;
                form.setValues({fatherMenuName:parentNode.text});
            },
            scope:node,
            waitMsg:'Loading..'
        });//end load 参数设置       
    });
    
    //放的事件
    tree.on({
        //添加拖过事件
        nodedragover:function(e){
            var node=e.target;
            if(node.leaf){
                node.leaf=false;
            }
            return true;
        },
        //放节点时触发的函数
        nodedrop:function(e){
            var item={
                dropNode:e.dropNode.id,
                target:e.target.id,
                point:e.point
            }
            var params='data='+encodeURIComponent(Ext.encode(item));
            Ext.Ajax.request({                 //调用Ajax发送请求到后台
                url:sortUrl,                    //删除grid数据的url.
                success:function(transport){                //处理成功后返回的函数
                    var oXmlDom=transport.responseText;
                    if(oXmlDom!=''){                  
                        var content=eval(oXmlDom);
                        Ext.MessageBox.alert("有错误：",content.errors)
                    }else{
                        Ext.MessageBox.alert('消息：','操作成功');
                    }
                },
                failure:function(){             //处理后台删除失败的函数
                    Ext.MessageBox.alert('消息','操作失败!');
                },
                params:params
            });
        }
    });
    
    var viewport = new Ext.Viewport({
        layout : 'border',
        items : [
        {
            region : 'west',
            margins : '0 0 0 0',
            cmargins : '5 5 0 5',
            width : 280,
            minSize : 100,
            maxSize : 300,
            items : [tree]
        }, form]

    });

    //给树空白添加右键菜单
    var treeP =  tree.getEl().parent();
    treeP.on('contextmenu',function(e){
        e.preventDefault();                 //禁止默认菜单弹出
        treeContextmenu.showAt(e.getXY());
    });
})